package com.cssnj.portal.web.realm;


import com.cssnj.portal.domain.common.UserInfo;
import com.cssnj.portal.service.login.LoginService;
import com.cssnj.portal.utils.PortalUntil;
import io.predictech.framework.utility.StringUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


public class PortalRealm extends AuthorizingRealm {


    @Autowired
    private LoginService loginService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        s.setStringPermissions(userInfo.getPermissions());
        s.setRoles(userInfo.getRole());
        return s;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        String userJson = token.getPrincipal().toString();
        UserInfo userInfo = null;
        try {
            userInfo = StringUtil.getBaseObjectMapper().readValue(userJson, UserInfo.class);
            t.setUsername(userInfo.getDlzhDm());
            SimpleAuthenticationInfo simpleAuthenticationInfo = null;
            simpleAuthenticationInfo = new SimpleAuthenticationInfo(userInfo, t.getPassword(), getName());
            return simpleAuthenticationInfo;
        } catch (Exception e) {
            PortalUntil.logger().error(e.getMessage());
            throw new AuthenticationException("抱歉，系统暂时无法访问,请稍后再试");
        }
    }

}
